/**
 * 上传文件
 */
import urlConfig from '@/common/config.js';

/**
 * 上传图片
 * @param {Object} path
 */
export function uploadImage(count = 9){
	return new Promise(function(resolve, reject) {		
		// 选择媒体
		uni.chooseMedia({
			count: count,
			mediaType: ['image'],
			sizeType: ['compressed'], 
			sourceType: ['album'], 
			success: (res) => {
				const tempFilePaths = res.tempFiles
				let images = []
				let index = 0
				tempFilePaths.forEach((item,key) => {
					// 上传
					uni.uploadFile({
						url: urlConfig + 'api/upload', 
						filePath: item.tempFilePath,
						name: 'file',
						fileType: "image",
						header: {'Authorization': uni.getStorageSync("token")},
						success: (response) => {
							index++
							const { code, data } = JSON.parse(response.data.trim());
							if(code == 0){
								let filepath = data.filepath.replace(/\\/g, '/');
								images.push(urlConfig + filepath)
							}
							if(tempFilePaths.length == index) {
								return resolve(images)						
							}
						}
					})
				})
			},
			fail: (err)=> {
				console.log(JSON.stringify(err))
				return reject()
			}
		})
	})		
}